import { getStore, setStore, removeStore } from '@/utils/store'
import { defineStore } from 'pinia'
import { login, logout } from '@/api/login'

export const useUserStore = defineStore('user', {
  state: () => ({
    access_token:
      getStore({
        name: 'access_token'
      }) || '',
    refresh_token:
      getStore({
        name: 'refresh_token'
      }) || '',
    userInfo: getStore({ name: 'userInfo' }) || {},
    tags: getStore({ name: 'tags' }) || [],
    themeColor:
      getStore({
        name: 'themeColor'
      }) || '#409eff',
    headerBgColor: getStore({ name: 'headerBgColor' }) || '#151515',
    menuColor: getStore({ name: 'menuColor' }) || {
      bgColor: '#ffffff',
      subBgColor: '#ffffff'
    }
  }),
  actions: {
    LoginByUserName(userName, password) {
      return new Promise((resolve, reject) => {
        login(userName, password)
          .then((res) => {
            console.log(res)
            let data = res.data.data
            this.access_token = data.token
            this.refresh_token = data.refreshToken
            this.userInfo = data.user
            setStore({
              name: 'access_token',
              content: data.accessToken
            })
            setStore({
              name: 'refresh_token',
              content: data.refreshToken
            })
            setStore({
              name: 'userInfo',
              content: data.userInfo
            })
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    LogOut(id) {
      return new Promise((resolve, reject) => {
        logout(id)
          .then((res) => {
            this.access_token = ''
            this.refresh_token = ''
            this.userInfo = {}
            removeStore({
              name: 'access_token'
            })
            removeStore({
              name: 'refresh_token'
            })
            removeStore({
              name: 'userInfo'
            })
            resolve()
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    setTags(tag) {
      this.tags.push(tag)
      setStore({
        name: 'tags',
        content: this.tags
      })
    },
    delTags(index) {
      this.tags.splice(index, 1)
      setStore({
        name: 'tags',
        content: this.tags
      })
    },
    setThemeColor(color) {
      this.themeColor = color
      setStore({
        name: 'themeColor',
        content: this.themeColor
      })
    },
    setHeaderBgColor(color) {
      this.headerBgColor = color
      setStore({
        name: 'headerBgColor',
        content: this.headerBgColor
      })
    },
    setMenuColor(color) {
      this.menuColor = color
      setStore({
        name: 'menuColor',
        content: this.menuColor
      })
    }
  }
})
